package com.bb.blog.biz.manage.service;


import com.bb.blog.biz.manage.constant.ManageExceptionEnum;
import com.bb.blog.biz.manage.dao.SysMenuMapper;
import com.bb.blog.biz.manage.model.SysMenu;
import com.bb.blog.web.exception.ServerException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl implements SysMenuService {
    private final SysMenuMapper menuMapper;

    /**
     * 查询菜单
     */
    @Override
    public List<SysMenu> menuList(String systemId, Integer userId, List<Byte> status) {
        Example example = new Example(SysMenu.class);
        Example.Criteria criteria = example.createCriteria();
        if (systemId != null) {
            criteria.andEqualTo("systemId", systemId);
        }
        if (!CollectionUtils.isEmpty(status)) {
            criteria.andIn("status", status);
        }

        return menuMapper.selectByExample(example);
    }

    @Override
    public void addMenu(SysMenu sysMenu) {
        Boolean existsMenu = menuMapper.existsByCode(sysMenu.getCode());
        Boolean parentExists = true;
        if (existsMenu) {
            throw new ServerException(ManageExceptionEnum.MENU_CODE_DUPLICATED);
        }
        if (!StringUtils.isEmpty(sysMenu.getPcode())) {
            parentExists = menuMapper.existsByCode(sysMenu.getPcode());
        }
        if (!parentExists) {
            throw new ServerException(ManageExceptionEnum.MENU_CODE_DUPLICATED);
        }

        menuMapper.insertSelective(sysMenu);
    }

    @Override
    public void delMenu(Integer id) {
        SysMenu sysMenu = menuMapper.selectByPrimaryKey(id);
        doDelMenu(sysMenu);
    }

    @Override
    public void editMenu(SysMenu sysMenu) {
        menuMapper.updateByPrimaryKeySelective(sysMenu);
    }

    /**
     * 确保sysMenu是最新的数据库数据
     */
    private void doDelMenu(SysMenu dbMenu){
        if(dbMenu != null){
            List<SysMenu> children = menuMapper.selectByPcode(dbMenu.getCode());
            for (SysMenu child : children) {
                doDelMenu(child);
            }
        }

    }




}
